"use client"

import { useState, useEffect } from 'react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card'
import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { getPlayers, resetDatabase } from '@/lib/data'
import { useToast } from '@/components/ui/use-toast'
import AdminDashboard from '@/components/admin/dashboard'
import PlayersManager from '@/components/admin/players-manager'
import PlayerTiersManager from '@/components/admin/player-tiers-manager'
import RegionsManager from '@/components/admin/regions-manager'
import Login from '@/components/admin/login'
import { Database, AlertTriangle, LogOut } from 'lucide-react'
import { Player } from '@/types/player'

export default function AdminPage() {
  const [resetDialogOpen, setResetDialogOpen] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [selectedPlayerId, setSelectedPlayerId] = useState<string | null>(null)
  const [players, setPlayers] = useState<Player[]>([])
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const { toast } = useToast()

  // 检查用户是否已经登录
  useEffect(() => {
    const checkAuth = () => {
      // 先检查session storage
      const sessionAuth = sessionStorage.getItem('admin_auth')
      // 再检查local storage
      const localAuth = localStorage.getItem('admin_auth')
      
      if (sessionAuth || localAuth) {
        setIsAuthenticated(true)
      }
      
      setIsLoading(false)
    }
    
    // 由于涉及到localStorage和sessionStorage，
    // 需要在客户端渲染后执行
    checkAuth()
  }, [])

  useEffect(() => {
    // 只有在已认证状态下才加载数据
    if (isAuthenticated) {
      // 初始加载玩家数据
      const loadInitialData = async () => {
        try {
          const data = await getPlayers()
          setPlayers(data)
        } catch (err) {
          console.error('初始加载玩家数据失败:', err)
        }
      }
      
      loadInitialData()
    }
  }, [isAuthenticated])

  // 更新玩家数据的函数，将传递给子组件
  const updatePlayersData = (newPlayers: Player[]) => {
    setPlayers(newPlayers)
  }

  const handleResetDatabase = async () => {
    try {
      await resetDatabase()
      setResetDialogOpen(false)
      
      toast({
        title: "重置成功",
        description: "数据库已成功重置",
      })
      
      // 可以添加刷新页面或重新加载数据的逻辑
      window.location.reload()
    } catch (err: any) {
      console.error('重置数据库失败:', err)
      setError('重置数据库失败，请稍后重试')
      
      toast({
        variant: "destructive",
        title: "重置失败",
        description: "数据库重置操作失败，请稍后重试",
      })
    }
  }

  const handleLoginSuccess = () => {
    setIsAuthenticated(true)
  }

  const handleLogout = () => {
    // 清除存储的凭据
    sessionStorage.removeItem('admin_auth')
    localStorage.removeItem('admin_auth')
    
    // 更新状态
    setIsAuthenticated(false)
    
    toast({
      title: "已登出",
      description: "您已成功退出管理系统",
    })
  }

  // 加载中状态
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[calc(100vh-130px)]">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-4"></div>
          <p className="text-gray-400">正在加载...</p>
        </div>
      </div>
    )
  }

  // 如果未认证，显示登录表单
  if (!isAuthenticated) {
    return <Login onLoginSuccess={handleLoginSuccess} />
  }

  // 已认证，显示管理界面
  return (
    <div className="space-y-6">
      {/* 登出按钮 */}
      <div className="flex justify-end">
        <Button 
          variant="ghost" 
          onClick={handleLogout}
          className="flex items-center gap-2 text-red-400 hover:text-red-300 hover:bg-red-950/20"
        >
          <LogOut className="h-4 w-4" />
          退出登录
        </Button>
      </div>
      
      {error && (
        <div className="p-4 rounded-lg bg-red-950 border border-red-800 text-red-200">
          <div className="flex items-center gap-2 mb-2">
            <AlertTriangle className="h-5 w-5" />
            <h3 className="font-semibold">错误</h3>
          </div>
          <p>{error}</p>
        </div>
      )}

      <Tabs defaultValue="dashboard" className="w-full">
        <TabsList className="grid w-full grid-cols-4 mb-6">
          <TabsTrigger 
            value="dashboard"
            className="data-[state=active]:bg-blue-600 data-[state=active]:text-white"
          >
            控制面板
          </TabsTrigger>
          <TabsTrigger 
            value="players"
            className="data-[state=active]:bg-blue-600 data-[state=active]:text-white"
          >
            玩家管理
          </TabsTrigger>
          <TabsTrigger 
            value="tiers"
            className="data-[state=active]:bg-blue-600 data-[state=active]:text-white"
          >
            段位管理
          </TabsTrigger>
          <TabsTrigger 
            value="regions"
            className="data-[state=active]:bg-blue-600 data-[state=active]:text-white"
          >
            地区管理
          </TabsTrigger>
        </TabsList>
        
        {/* 控制面板 */}
        <TabsContent value="dashboard">
          <AdminDashboard />
        </TabsContent>
        
        {/* 玩家管理 */}
        <TabsContent value="players">
          <PlayersManager onPlayersUpdate={updatePlayersData} />
        </TabsContent>
        
        {/* 段位管理 */}
        <TabsContent value="tiers">
          <PlayerTiersManager 
            selectedPlayerId={selectedPlayerId} 
            onSelectPlayer={setSelectedPlayerId}
            players={players}
          />
        </TabsContent>
        
        {/* 地区管理 */}
        <TabsContent value="regions">
          <RegionsManager />
        </TabsContent>
      </Tabs>
      
      {/* 系统设置卡片 */}
      <Card className="border border-gray-800 bg-[#1a1d24]">
        <CardHeader>
          <CardTitle>系统设置</CardTitle>
          <CardDescription>数据库和系统维护操作</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="border border-red-900 bg-red-950/20 rounded-lg p-4">
            <h3 className="text-lg font-medium mb-2 text-red-300">危险区域</h3>
            <p className="text-gray-400 mb-4">
              以下操作可能会导致数据丢失，请谨慎操作。
            </p>
            <Button 
              variant="destructive" 
              onClick={() => setResetDialogOpen(true)}
              className="flex items-center gap-2 bg-red-700 hover:bg-red-800"
            >
              <Database className="h-4 w-4" />
              重置数据库
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 重置数据库确认对话框 */}
      <AlertDialog open={resetDialogOpen} onOpenChange={setResetDialogOpen}>
        <AlertDialogContent className="bg-[#1a1d24] border-gray-800 text-white">
          <AlertDialogHeader>
            <AlertDialogTitle>确认重置数据库?</AlertDialogTitle>
            <AlertDialogDescription className="text-gray-400">
              此操作将清空所有玩家数据，该操作无法撤销。确定要继续吗？
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="bg-transparent border-gray-700 hover:bg-gray-800 hover:text-white">
              取消
            </AlertDialogCancel>
            <AlertDialogAction 
              onClick={handleResetDatabase}
              className="bg-red-600 hover:bg-red-700 text-white focus:ring-red-600"
            >
              确认重置
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
} 